package com.zhrenjie04.alex.manager.controller.outter.fore;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhrenjie04.alex.core.JsonResult;
import com.zhrenjie04.alex.core.Permission;
import com.zhrenjie04.alex.core.User;
import com.zhrenjie04.alex.manager.service.UserService;
import com.zhrenjie04.alex.util.Md5Util;
import com.zhrenjie04.alex.util.SessionUtil;

/**
 * @author 张人杰
 */
@Controller
@RequestMapping("/user/fore")
@Permission("fore")
public class UserForeController {
	private final static Logger logger = Logger.getLogger(UserForeController.class);

	@Autowired
	UserService userService;

	@RequestMapping(value = "/user-info", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@Permission("modify-user-info")
	@ResponseBody
	public JsonResult modifyUserInfo(HttpServletRequest request, @RequestBody @Validated User object,
			BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			StringBuilder sb = new StringBuilder();
			int count = 0;
			for (FieldError error : bindingResult.getFieldErrors()) {
				if ("password".equals(error.getField()) && object.getNotChangePassword()) {
					continue;
				}
				++count;
				sb.append(error.getDefaultMessage()).append(";");
			}
			if (count > 0) {
				sb.deleteCharAt(sb.length() - 1);
				throw new RuntimeException(sb.toString());
			}
		}
		User currentUser = SessionUtil.getSessionUser(request);
		if (!currentUser.getUserId().equals(object.getUserId())) {
			throw new RuntimeException("您不能修改其他人的个人信息");
		}
		if (!currentUser.getUsername().equals(object.getUsername())) {
			throw new RuntimeException("用户名不能修改");
		}
		// 验证旧密码
		User oldUser = userService.queryObjectById(object.getUserId());
		if (oldUser == null || oldUser.getIsLocked() || oldUser.getIsDeleted()) {
			throw new RuntimeException("您的账号已被锁定，不能修改");
		}
		if (!Md5Util.encrypt(object.getOldPassword() + oldUser.getSalt()).equals(oldUser.getPassword())) {
			throw new RuntimeException("您输入的旧密码不正确");
		}
		// 更新
		userService.updateObject(object);
		return JsonResult.success();
	}
}
